#pragma once
#include <QObject>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonArray>
#include <QFile>
#include <QTcpSocket>
#include <QMutex>
#include "HiFileTransferDef.h"

class HiFileReceiver : public QObject
{
	Q_OBJECT
protected:
	HiFileReceiver(qintptr socketDescriptor, const QStringList& savePaths, qint64 minRemainSpace);
	~HiFileReceiver();

public:
	QString getId() const;
	QString getIp() const;

signals:
	void signalClose();
	void signalReceiveDataSize(const qint64 nSize);
	void signalFileReceiveFinished(const QString& filePath, const QByteArray& userData);
	void signalReceiveStart();
	void signalReceiveError(HiFileTransferDef::eRecevieError);

protected slots:
	void onSocketDisconnected();
	void onMessageReceived();

private:
	void reply(HiFileTransferDef::eRevFileCmd cmd, const QJsonObject& param);

private:
	QString mId;
	QTcpSocket* mSocket;
	QString mIp;
	QStringList mSavePathList;
	qint64 mMinRemainSpace = 0;
	QFile *mFile = nullptr;

	QString mRelativeFilePath;
	QString mFilePath;
	QString mTempFilePath;
	QByteArray mUserData;
	qint64 mFileSize = 0;

	friend class HiFileReceiverManager;
};

class HiFileReceiverManager : public QObject
{
protected:
	HiFileReceiverManager();
	~HiFileReceiverManager();

public:
	static HiFileReceiverManager* getInstance();

public:
	HiFileReceiver* createReceiver(qintptr socketDescriptor, const QStringList& savePaths, qint64 minRemainSpace);
	void destroyReceiver(HiFileReceiver*);
	QMap<QString, HiFileReceiver*> getAllReceivers();
	QMap<QString, HiFileReceiver*>::const_iterator getAllReceiversBeginIterator();

private:
	QMap<QString, HiFileReceiver*> mIdAndReceiverMap;
	QMap<HiFileReceiver*, QThread*> mReceiverAndThreadMap;
	static QMutex mLock;
	static HiFileReceiverManager* mInstance;
};
HiFileReceiverManager* getFileReceiverManager();